from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from shunt.models import Verse, Book,  Game
from django.http import HttpResponseRedirect
from django import *
from shunt.forms import RegisterForm
#from shunt.importing import ImportForm
import random 
from shunt.helper import *
from django.contrib import messages

def index(request):
    verse_id = int(request.GET.get('verse_id',  0))
    session_verse_id = int(request.session.get("verse_id",  1))
    
    if verse_id == session_verse_id:
        messages.add_message(request, messages.SUCCESS, 'Yeah, richtig')
        if request.user.is_authenticated():
            game = Game(uid=request.user, won=True)
            game.save()
    elif verse_id != session_verse_id and verse_id != 0:
        correct_verse = Verse.objects.get(pk=session_verse_id)
        
        messages.add_message(request, messages.INFO, 'Leider falsch. Richtig Antwort: ' + correct_verse.get_reference() )
        messages.add_message(request,  messages.INFO,  correct_verse.verse_scripture)
        
        if request.user.is_authenticated():
            game = Game(uid=request.user, won=False)
            game.save()
    
    #prepare the scripturelist for the templates
    random_scripture = Verse.objects.all().order_by('?')[:3]
    scriptures = []
    for scripture in random_scripture:
        scriptures.append(scripture)
    
    request.session["verse_id"] = scriptures[0].verse_id
    random.shuffle(scriptures)
    
    scripture_of_the_day = get_scripture_of_the_day()
        
    request.GET = request.GET.copy()
    request.GET.update({'verse_id':0})
    return render_to_response("shunt/random.html", locals(), context_instance=RequestContext(request))
    
def ranking(request):
    sql = "SELECT s.id, uid_id, count(won) as numb_won, u.username FROM shunt_game s, auth_user u WHERE won=1 AND s.uid_id=u.id group by uid_id order by numb_won desc LIMIT 0,10"
    games = Game.objects.raw(sql)
    scripture_of_the_day = get_scripture_of_the_day()
    return render_to_response("shunt/ranking.html",  locals(),  context_instance=RequestContext(request))
    
def debug(request):
    values = request.META.items()
    values.sort()
    html = []
    for k, v in values:
        html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
    content = '<table>%s</table>' % '\n'.join(html)
    return render_to_response("shunt/debug.html",  locals(), context_instance=RequestContext(request))
    
#def importing(request):
#    if request.method == 'POST':
#        form = ImportForm(request.FILES)
#        message = form.handle_uploaded_file(request.FILES['file'])
#        #return render_to_response("shunt/import.html", {'message': message})
#    form = ImportForm()
#    return render_to_response("shunt/import.html", {'form': form}, context_instance=RequestContext(request))
